package com.educhains.web.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * 计算文件MD5，用来校验文件
 */
public class FileHashUtils {

    private static byte[] getMD5ByteArray(String fileName) throws Exception {
        InputStream in = new FileInputStream(fileName);

        byte[] buffer = new byte[1024];
        MessageDigest md = MessageDigest.getInstance("MD5");

        int numRead;
        do {
            numRead = in.read(buffer);
            if(numRead > 0) {
                md.update(buffer, 0, numRead); // 用读到的字节进行MD5的计算，第二个参数是偏移量
            }
        } while( numRead != -1);

        in.close();
        return md.digest();
    }

    /**
     * 获取MD5值，就算是文件Hash值
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String getMD5HashCode(String fileName) throws Exception {
        byte[] b = getMD5ByteArray(fileName);
        String result = "";

        for(int i = 0; i < b.length; i++) {
            result += Integer.toString(( b[i] & 0xff ) + 0x100, 16).substring(1);
        }

        return result;
    }
}
